package cn.bdqn.controller;

import java.io.File;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.bdqn.dao.UsersMapper;
import cn.bdqn.entity.Address;
import cn.bdqn.entity.Repair;
import cn.bdqn.entity.Users;
import cn.bdqn.entity.UsersAndComVo;
import cn.bdqn.service.AddressService;
import cn.bdqn.service.ComplaintsService;
import cn.bdqn.service.RepairService;
import cn.bdqn.service.UsersService;
import cn.bdqn.util.MailUtil;
import cn.bdqn.util.Page;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

@Controller
@RequestMapping("users")
public class UsersController {
	@Autowired
	private UsersService service;
	@Autowired
	private ComplaintsService comservice;
	@Autowired
	private RepairService reservice;
	@Autowired
	private AddressService addservice;
	
	
	
	
	@RequestMapping("login")
	public String UsersLogin(Users users, HttpSession session,Model model,String context, Integer pageNo,Integer pageSize) {
		
		Users users1=service.queryLogin(users);
		if(users1!=null) {
			session.setAttribute("userlogin", users1);
			if(pageNo==null) {
				pageNo=1;
			}
			if(pageSize==null) {
				pageSize=2;
			}
			Page<UsersAndComVo> page=new Page<>();
			page.setPageSize(pageSize);
			page.setPageNo(pageNo);
			comservice.queryAllComplaints(context, page);
			List<Repair> list=reservice.queryAllRepairByUserid(users1.getUserid());
			model.addAttribute("page", page);
			model.addAttribute("list", list);
			
			return "main";
		}
		model.addAttribute("username", users.getUsername());
		model.addAttribute("message", "密码错误，请重新输入密码");
		return "index";
	}
	@ResponseBody
	@RequestMapping(value="ajaxUserName",produces= {"application/json;charset=UTF-8"})
	public String ajaxUserName(String username) {
		Users users=service.queryUserName(username);
		if(users!=null) {
			return JSON.toJSONString(users);
		}
		return JSON.toJSONString(users);
	}
	//验证数据库中是否存在此邮箱
	@ResponseBody
	@RequestMapping(value="ishaveemail",produces= {"application/json;charset=UTF-8"})
	public String ishaveemail(String email) {
		Users user=service.queryUserEmail(email);
		if(user!=null) {
			return JSON.toJSONString(user);
		}
		return JSON.toJSONString(user);
	}
	//邮箱验证ajax
	@ResponseBody
	@RequestMapping(value="ajaxemail",produces= {"application/json;charset=UTF-8"})
	public String ajaxEmail(String email) {
		String num1="";
		try {
        	num1=String.valueOf((int)(Math.random()*8999)+1000);
        	System.out.println(num1);
            MailUtil.send_mail(email, "尊敬的"+email+"用户您好：欢迎您注册 空城科技 您的验证码为："+num1+"，请您尽快填写验证码，以防失效，谢谢合作，如有其他人索要验证码，请勿告知。");
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败!");
        }
		return JSON.toJSONString(num1);
	}
	//邮箱验证成功后进行登录
	@RequestMapping("emaillogin")
	public String emailLogin(String email,HttpSession session,Model model,String context, Integer pageNo,Integer pageSize) {
		Users users=service.queryUserEmail(email);
		if(users!=null) {
			session.setAttribute("userlogin", users);
			if(pageNo==null) {
				pageNo=4;
			}
			if(pageSize==null) {
				pageSize=2;
			}
			Page<UsersAndComVo> page=new Page<>();
			page.setPageSize(pageSize);
			page.setPageNo(pageNo);
			comservice.queryAllComplaints(context, page);
			List<Repair> list=reservice.queryAllRepairByUserid(users.getUserid());
			model.addAttribute("page", page);
			model.addAttribute("list", list);
			return "main";
		}
		model.addAttribute("message", "登录失败，请重新登录！");
		return "index";
	}
	//退出登录
	@RequestMapping("outlogin")
	public String outLogin(HttpSession session,HttpServletResponse response) {
        session.removeAttribute("userlogin");
        response.setHeader("Cache-Control","no-cache"); //不对页面进行缓存，再次访问时将从服务器重新获取最新版本
		response.setHeader("Cache-Control","no-store"); //任何情况下都不缓存页面
		response.setDateHeader("Expires", 0); //使缓存过期
		response.setHeader("Pragma","no-cache"); //HTTP 1.0 向后兼容
		return "index";
	}
	//分页
	@RequestMapping("page")
	public String topage(String context,Integer pageNo,Integer pageSize,Model model,HttpSession session) {
		context="";
		if(pageNo==null) {
			pageNo=1;
		}
		if(pageSize==null) {
			pageSize=2;
		}
		System.out.println("lllllllllll"+pageNo);
		Users users1=(Users) session.getAttribute("userlogin");
		List<Repair> list=reservice.queryAllRepairByUserid(users1.getUserid());
		model.addAttribute("list", list);
		Page<UsersAndComVo> page=new Page<>();
		page.setPageSize(pageSize);
		page.setPageNo(pageNo);
		comservice.queryAllComplaints(context, page);
		model.addAttribute("page", page);
		return "main";
	}
	//分页
	@RequestMapping("page1")
	public String topage1(String context,Integer pageNo,Integer pageSize,Model model,HttpSession session) {
		if(pageNo==null) {
			pageNo=1;
		}
		if(pageSize==null) {
			pageSize=2;
		}
		Users users1=(Users) session.getAttribute("userlogin");
		List<Repair> list=reservice.queryAllRepairByUserid(users1.getUserid());
		model.addAttribute("list", list);
		Page<UsersAndComVo> page=new Page<>();
		page.setPageSize(pageSize);
		page.setPageNo(pageNo);
		model.addAttribute("context",context);
		comservice.queryAllComplaints(context, page);
		model.addAttribute("page", page);
		return "main";
	}
	//重定向首页
	@RequestMapping("redirct")
	public String toredirct(HttpSession session) {
		Users user=(Users) session.getAttribute("userlogin");
		Users users=new Users();
		users.setUsername(user.getUsername());
		users.setPassword(user.getPassword());
		return "forward:/users/login?username="+user.getUsername()+"&password="+user.getPassword();
	}
	@RequestMapping("toshouye")
	public String toshouye(HttpSession session,Integer pageNo,Integer pageSize,String context,Model model) {
		Users users1=(Users) session.getAttribute("userlogin");
		if(pageNo==null) {
			pageNo=1;
		}
		if(pageSize==null) {
			pageSize=2;
		}
		Page<UsersAndComVo> page=new Page<>();
		page.setPageSize(pageSize);
		page.setPageNo(pageNo);
		comservice.queryAllComplaints(context, page);
		List<Repair> list=reservice.queryAllRepairByUserid(users1.getUserid());
		model.addAttribute("page", page);
		model.addAttribute("list", list);
		return "shouye";
	}
	@RequestMapping("touserinfo")
	public String touserinfo(Integer userid,Model model,HttpSession session) {
		Users users=(Users) session.getAttribute("userlogin");
		Address add=addservice.queryAddressById(users.getFloorid());
		model.addAttribute("lou", add.getName());
		Address ceng=addservice.queryAddressById(users.getLayerid());
		model.addAttribute("ceng", ceng.getName());
		Address room=addservice.queryAddressById(users.getRoomid());
		model.addAttribute("room", room.getName());
		Users user=service.queryUserByuserid(userid);
		model.addAttribute("users", user);
		return "userinfo1";
	}
	
	@RequestMapping("updateUsers")
	public String updateUsers(Users users,Model model) {
		Integer count=service.updateUsers(users);
		model.addAttribute("message", "更新数据成功");
		return "forward:/users/touserinfo";
		
		
	}
	//跳转找回密码
	@RequestMapping("toforgetpassword")
	public String forgetpassword(String name,Model model) {
		if(name!=null||name!="") {
			model.addAttribute("name", name);
		}
		return "forgetPassword";
	}
	//跳转到修改密码页面
	@RequestMapping("toupdatepassword")
	public String toupdatepassword() {
		return "updatepassword";
	}
	//忘记密码，修改密码时，需要ajax获取到userid
	@ResponseBody
	@RequestMapping(value="queryUserid",produces= {"application/json;charset=UTF-8"})
	public String queryuserid(String email) {
		Users user=service.queryUserEmail(email);
		return JSON.toJSONString(user); 
	}
	//忘记密码，修改完密码后跳转页面
	@RequestMapping("updatepasswordsucess")
	public String xiugaimima(Users users,Model model) {
		Integer count=service.updateUsers(users);
		model.addAttribute("message", "更新数据成功,快去登录吧");
		return "updatepassword";
	}
	//修改成功后点击确定跳转登录页面
	@RequestMapping("tologin")
	public String tologin() {
		return "index";
	}
	//跳转调整宿舍页面
	@RequestMapping("tohuansushe")
	public String tohuansushe(Integer floorid,Integer layerid,Integer roomid,String username,Integer pageNo,Integer pageSize,Model model) {
		if(pageNo==null) {
			pageNo=1;
		}
		if(pageSize==null) {
			pageSize=2;
		}
		if(username==null) {
			username="";
		}
		if(floorid==null) {
			floorid=0;
		}
		if(layerid==null) {
			layerid=0;
		}
		if(roomid==null) {
			roomid=0;
		}
		Page<Users> page=new Page<>();
		page.setPageSize(pageSize);
		page.setPageNo(pageNo);
		List<Address> addlist=addservice.queryAllAddress(-1);
		List<Address> alladd=addservice.queryAll();
		model.addAttribute("alladd", alladd);
		model.addAttribute("addlist", addlist);
		model.addAttribute("username", username);
		service.queryUsers(username, floorid, layerid, roomid, page);
		model.addAttribute("page", page);
		return "huansushe";
	}
	//调换宿舍
	@RequestMapping("detailUsers")
	public String detailUsers(Integer userid,Model model) {
		List<Address> addlist=addservice.queryAllAddress(-1);
		model.addAttribute("addlist", addlist);
		Users users=service.queryUserByuserid(userid);
		model.addAttribute("users", users);
		return "updatesushe";
	}
	//楼管修改宿舍信息
	@RequestMapping("updatesushe")
	public String updatesushe(Users users,Model model) {
		Integer count=service.querypersonnum(users.getFloorid(), users.getLayerid(), users.getRoomid());
		if(count<6) {
			Integer num=service.updateUsers(users);
		}else {
			model.addAttribute("message", "该宿舍人员已经满了，请调换宿舍！");
		}
		return "forward:/users/tohuansushe?floorid=0&layerid=0&roomid=0";
	}
	//修改个人头像
	@RequestMapping("updateheadimg")
	public String updateheadimg(Users users,HttpSession session, HttpServletRequest request,Model model,@RequestParam(value="a_idPicPath",required=false) MultipartFile attach) {
		String postimg=null;
		//判断文件是否为空
		if(!attach.isEmpty()) {
			//定义文件上传路径
			String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"images");
			String oldFileName=attach.getOriginalFilename();
			String prefix=FilenameUtils.getExtension(oldFileName);
			int filesize=5000000;
			if(attach.getSize()>filesize) {
				request.setAttribute("message", "* 文件大小不得超过5000k");
				return "main";
			}else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("pneg")) {
				//获取当前系统时间和随机数+"_Personal.jpg"
				String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
				File targetFile=new File(path, fileName);
				if(!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("message", "* 上传失败");
					return "main";
				}
				postimg="/dormitory/statics/images/"+File.separator+fileName;
			}else {
				request.setAttribute("message", "* 上传图片格式必须是jpg、jpeg、png、pneg");
				return "main";
			}
			users.setHeadimg(postimg);
		}
		Integer num=service.updateUsers(users);
		model.addAttribute("messag", "更换成功");
		return "forward:/users/touserinfo";
	}
	@RequestMapping("toaddusers")
	public String toaddusers(Model model) {
		List<Address> addlist=addservice.queryAllAddress(-1);
		model.addAttribute("addlist", addlist);
		return "addusers";
	}
	@RequestMapping("saveUsers")
	public String saveusers(Users users,Model model) {
		Integer count=service.querypersonnum(users.getFloorid(), users.getLayerid(), users.getRoomid());
		if(count<6) {
			Integer num=service.saveusers(users);
			model.addAttribute("message", "注册成功");
		}else {
			model.addAttribute("message", "对不起，该房间已经住满了");
		}
		return "forward:/users/toaddusers";
	}
	@RequestMapping("deleteUsers")
	public String deleteUsers(Integer userid,Model model) {
		service.deleteUsers(userid); 
		model.addAttribute("message", "移出成功！");
		return "forward:/users/tohuansushe?floorid=0&layerid=0&roomid=0";
	}
	//手机号验证码登录页面跳转
	@RequestMapping("ToPhoneLogin")
	public String tophonelogin() {
		return "phoneLogin";
	}
	//手机号登录，输入手机号，发送验证码
	@ResponseBody
	@RequestMapping(value="phoneLogin",produces= {"application/json;charset=UTF-8"})
	public String PhoneLogin(String phone) {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FmVQWibiPkmvwZwvi8y", "OkxOKVPFnGk0FVy0jQQA68g6Weq9Lk");
        IAcsClient client = new DefaultAcsClient(profile);
        String codema=String.valueOf((int)(Math.random()*8999)+1000);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "宿舍管理");
        request.putQueryParameter("TemplateCode", "SMS_173475393");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+codema+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
		return JSON.toJSONString(codema);
		
		
		
		
		
		
	}
	
	
}
